package com.android.tio.client;

import com.android.tio.core.ChannelContext;
import com.android.tio.core.Node;
import com.android.tio.core.TioConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author tanyaowu
 * 2017年4月1日 上午9:31:16
 */
public class ClientChannelContext extends ChannelContext {

    private String bindIp;

    private Integer bindPort;

    private ReconnRunnable reconnRunnable;

    /**
     * 连续重连次数，连接成功后，此值会被重置0
     */
    private AtomicInteger reconnCount = new AtomicInteger();

    /**
     * @param tioConfig
     * @param asynchronousSocketChannel
     * @author tanyaowu
     */
    public ClientChannelContext(TioConfig tioConfig, AsynchronousSocketChannel asynchronousSocketChannel) {
        super(tioConfig, asynchronousSocketChannel);
    }

    /**
     * @param asynchronousSocketChannel
     * @return
     * @throws IOException
     * @author tanyaowu
     * 2016年12月6日 下午12:18:08
     */
    @Override
    public Node createClientNode(AsynchronousSocketChannel asynchronousSocketChannel) throws IOException {
        Node clientNode = null;
        InetSocketAddress inetSocketAddress = null;
        if (asynchronousSocketChannel == null) {
            clientNode = createUnknowNode();
        } else {
            inetSocketAddress = (InetSocketAddress) asynchronousSocketChannel.getLocalAddress();
        }

        if (inetSocketAddress == null) {
            clientNode = createUnknowNode();
        }

        if (clientNode == null) {
            clientNode = new Node(inetSocketAddress.getHostString(), inetSocketAddress.getPort());
        }
        return clientNode;
    }

    /**
     * @return the bindIp
     */
    public String getBindIp() {
        return bindIp;
    }

    /**
     * @return the bindPort
     */
    public Integer getBindPort() {
        return bindPort;
    }

    /**
     * @param bindIp the bindIp to set
     */
    public void setBindIp(String bindIp) {
        this.bindIp = bindIp;
    }

    /**
     * @param bindPort the bindPort to set
     */
    public void setBindPort(Integer bindPort) {
        this.bindPort = bindPort;
    }

    /**
     * @return
     * @author tanyaowu
     */
    @Override
    public boolean isServer() {
        return false;
    }

    public ReconnRunnable getReconnRunnable() {
        return reconnRunnable;
    }

    public void setReconnRunnable(ReconnRunnable reconnRunnable) {
        this.reconnRunnable = reconnRunnable;
    }

    public AtomicInteger getReconnCount() {
        return reconnCount;
    }

    public void setReconnCount(AtomicInteger reconnCount) {
        this.reconnCount = reconnCount;
    }

}
